<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/goods'}">项目管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加记录</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-alert title="添加记录信息" type="info" :closable="false" show-icon center> </el-alert>
      <el-steps :active="activeIndex - 0" finish-status="success" align-center :space="200">
        <el-step title="基本信息"></el-step>
        <!-- <el-step title="记录参数"></el-step>
        <el-step title="记录属性"></el-step> -->
        <el-step title="记录图片"></el-step>
        <el-step title="记录内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" label-position="top">
        <el-tabs tab-position="left" v-model="activeIndex" :before-leave='beforTabLeave' @tab-click='tabClicked'>
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="设备别名" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="设备编号" prop="goods_sn">
              <el-input v-model="addForm.goods_sn"></el-input>
            </el-form-item>
            <el-select v-model="addForm.goods_state" placeholder="请选择">
              <el-option
                v-for="item in stateList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>                     
            <el-form-item label="记录分类">
              <el-cascader v-model="addForm.goods_cat" :options="cateList" :props="cascaderProps" @change="handleChange"></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <!-- <el-tab-pane label="记录参数" name="1">
            <el-form-item v-for="item in manyData" :key="item.attr_id" :label="item.attr_name">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox v-for="(value,i) in item.attr_vals" :key="i" :label="value" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="记录属性" name="2">
            <el-form-item v-for="item in onlyData" :key="item.attr_id" :label="item.attr_name">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane> -->
          <el-tab-pane label="记录图片" name="3">
            <el-upload :action="uploadPath" :on-preview="handlePreview" :on-success='handleSuccess' :on-remove="handleRemove" :headers="headerObj" list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="记录内容" name="4">
            <quill-editor v-model="addForm.goods_introduce" />
            <el-button type="primary" class="btn-add" @click="addGoods()">添加记录</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <el-dialog title="图片预览" :visible.sync="previewVisible" width="80%" :close-on-click-modal="false">
      <img :src="previewPath" class="preview-img" />
    </el-dialog>
  </div>
</template>

<script>
import { uploadPath } from '../../../.env.development'
import _ from 'lodash'
export default {
  created() {
    this.getCateList()
  },
  data() {
    return {
      uploadPath,
      activeIndex: '0',
      addFormRules: {
        goods_name: [{ required: true, message: '请输入设备别名', trigger: 'blur' }],
        goods_sn: [{ required: true, message: '请输入设备编号', trigger: 'blur' }],
      },
      addForm: {
        goods_name: '',
        goods_sn: null,
        // 记录所属分类的数组
        goods_cat: [],
        // 图片的数组
        pics: [],
        // 记录的内容
        goods_introduce: '',
        // 记录的参数
        attrs: [],
      },
      headerObj: {
        Authorization: JSON.parse(sessionStorage.getItem('userInfo')).token,
      },
      previewVisible: false,
      cateList: [],
      stateList:[{
          value: '1',
          label: '在线'
        }, {
          value: '2',
          label: '离线'
        }],      
      manyData: [],
      onlyData: [],
      cascaderProps: {
        label: 'cat_name',
        value: 'cat_id',
        children: 'children',
        expandTrigger: 'hover',
      },
      previewPath: '',
      // selectedKeys: [],
      // cascadeProps: {
      //   label: 'cat_name',
      //   value: 'cat_id',
      //   expandTrigger: 'hover',
      //   checkStrictly: true,
      // },
    }
  },
  methods: {
    handlePreview(file) {
      this.previewVisible = true
      this.previewPath = file.url
      console.log(file)
    },
    handleSuccess(response) {
      this.addForm.pics.push({'pic':response.data.temp_path, pic_id:Math.floor(Math.random () * 9000)+1000})
      console.log('handleSuccess pics', this.addForm)
    },
    handleRemove(file) {
      const filePath = file.response.data.temp_path
      const i = this.addForm.pics.findIndex(item => item.pic === filePath)
      console.log('handleRemove i',i)
      this.addForm.pics.splice(i,1)
       console.log('handleRemove pics',this.addForm.pics)
    },
    async getCateList() {
      const { data: res } = await this.$http.get('cate_display/')
      this.cateList = res.data
      this.total = res.total
      console.log('add cate res', res.data)
      // this.$message.success('获取角色成功')
    },
    handleChange() {
      if(this.addForm.goods_cat.length !=3) {
        this.addForm.goods_cat = []
      }
    },
    beforTabLeave(activeName,oldActiveName) {
      if(this.addForm.goods_cat.length !=3) {
        this.$message.error('请先选择记录分类!')
        return false
      }
    },
  async tabClicked() {
    if(this.activeIndex === '1'){
        //获取具体记录分类的动态参数列表
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes/`, {
          params: { sel: 'many' },
        })
        res.data = JSON.parse(res.data)
        console.log('tabClicked many res', res.data)
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals?item.attr_vals.split(' '):[]
        })
        this.manyData = res.data
    }else if (this.activeIndex === '2') {
        //获取具体记录分类的静态属性列表
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes/`, {
          params: { sel: 'only' },
        })
        res.data = JSON.parse(res.data)
        console.log('tabClicked only res', res.data)
        this.onlyData = res.data
    }
  },
  addGoods() {
    this.$refs.addFormRef.validate(async valid => {
      if(!valid){
        return 
      }
      console.log('addGoods addForm',this.addForm)
      const form = _.cloneDeep( this.addForm)
      // form.goods_cat = form.goods_cat.join(',')
      // form.goods_cat = form.goods_cat[2]
      console.log('addGoods manyData',this.manyData)

      //处理动态参数
      this.manyData.forEach(item => {
        form.attrs.push(
          {
            'attr_id':item.attr_id,
            'attr_value':item.attr_vals.join(' ')
          }
        )
      })

      //处理静态属性
      this.onlyData.forEach(item => {
        form.attrs.push(
          {
            'attr_id':item.attr_id,
            'attr_value':item.attr_vals
          }
        )
      })

      //发送请求
      console.log('addGoods form', form)
      const {data:res} = await this.$http.post('goods/',form)
      console.log('addGoods res', res)
      this.$message.success('添加记录成功')
      this.$router.push('/goods')
    })
  }
  },
  computed: {
    cateId() {
      console.log('cateId 111', this.addForm.goods_cat)
      return this.addForm.goods_cat[2]
      // return this.addForm.goods_cat.length ===3 ? this.addForm.goods_cat[2]:null
    }
  },
}
</script>
<style lang="less" scoped>
.preview-img {
  width: 100%;
}
.el-checkbox{
  margin-right: 10px;
}
.btn-add{
  margin-top: 15px;
}
</style>